package com.ebt.m.customer.net.http;

import android.content.Context;

import com.ebt.m.AppContext;
import com.ebt.m.AppInitService;
import com.ebt.m.R;
import com.ebt.m.jpush.PushToken;
import com.ebt.m.customer.entity.Attachment;
import com.ebt.m.customer.entity.PolicyBean;
import com.ebt.m.customer.net.constant.HttpConfig;
import com.ebt.m.customer.net.json.ErrorJson;
import com.ebt.m.customer.net.json.PolicyAllJson;
import com.ebt.m.commons.model.http.APIsFactory;
import com.ebt.m.data.rxModel.api.EBTAPI;
import com.ebt.m.commons.utils.Logger;
import com.ebt.m.utils.UIHelper;
import com.ebt.m.commons.utils.NetUtils;
import com.google.gson.JsonObject;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 保单请求
 * Created by archer.qi on 2016/12/15.
 */
public class PolicyHttps {

    private Context mContext;

    private EBTAPI mPolicyApi;

    private static PolicyHttps instance;

    private boolean DEBUG = false;

    public static PolicyHttps getInstance(Context context) {
        if (instance == null) {
            synchronized (PolicyHttps.class) {
                if (instance == null) {
                    instance = new PolicyHttps(context);
                }
            }
        }
        return instance;
    }

    private PolicyHttps(Context context) {
        mContext = context;
        OkHttpClient.Builder httpClientBuilder = new OkHttpClient.Builder();
        httpClientBuilder.connectTimeout(HttpConfig.DEFAULT_TIMEOUT, TimeUnit.SECONDS);
        mPolicyApi = AppInitService.getEbtApi();
    }

    /**
     * 获取客户所有保单
     *
     * @param customerId
     * @param callback
     */
    public void getAllCustomerPolicys(String customerId, onResponseCallback callback) {
        mPolicyApi.getAllCustomerPolicys(customerId)
                .enqueue(new onCallResponse(0, callback));
    }

    /**
     * 分页获取客户保单
     *
     * @param customerId
     * @param callback
     */
    public void getCustomerPolicys(String customerId, int page, int pageSize, onResponseCallback callback) {
        mPolicyApi.getCustomerPolicys(customerId, page, pageSize)
                .enqueue(new onCallResponse(0, callback));
    }

    /**
     * 创建保单
     *
     * @param policy
     * @param callback
     */
    public void createCustomerPolicy(PolicyBean policy, onResponseCallback callback) {
        mPolicyApi.createPolicy(PolicyRequest.getCreatePolicyBody(policy))
                .enqueue(new onCallResponse(1, callback));
    }

    /**
     * 更新保单
     *
     * @param policy
     * @param callback
     */
    public void updateCustomerPolicy(PolicyBean policy, onResponseCallback callback) {
        mPolicyApi.updatePolicy(PolicyRequest.getUpdatePolicyBody(policy))
                .enqueue(new onCallResponse(1, callback));
    }

    /**
     * 删除保单
     *
     * @param policyId
     * @param callback
     */
    public void deleteCustomerPolicy(String policyId, onResponseCallback callback) {
        mPolicyApi.deletePolicy(policyId)
                .enqueue(new onCallResponse(1, callback));
    }

    /**
     * 创建保单附件
     *
     * @param policyId
     * @param attachments
     * @param callback
     */
    public void createPolicyAttachment(String policyId, List<Attachment> attachments, onResponseCallback callback) {
        mPolicyApi.createPolicyAttachment(policyId, PolicyRequest.getCreateAttachmentBody(attachments))
                .enqueue(new onCallResponse(2, callback));
    }

    /**
     * 创建保单附件
     *
     * @param policyId
     * @param attachments
     * @param callback
     */
    public void deletePolicyAttachment(String policyId, List<Attachment> attachments, onResponseCallback callback) {
        mPolicyApi.deletePolicyAttachment(policyId, PolicyRequest.getDeleteAttachmentBody(attachments))
                .enqueue(new onCallResponse(2, callback));
    }

    /**
     * 获取品牌列表
     *
     * @param page
     * @param pageSize
     */
    public void getCompanyList(int page, int pageSize, onResponseCallback callback) {
        mPolicyApi.getCompanyList(page, pageSize).enqueue(new onCallResponse(3, callback));
    }

    private class onCallResponse implements Callback<JsonObject> {

        private int flag;
        private onResponseCallback callback;

        public onCallResponse(int flag, onResponseCallback callback) {
            this.flag = flag;
            this.callback = callback;
        }

        @Override
        public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
            if (response == null) {
                ErrorJson errorJson = new ErrorJson();
                errorJson.code = "-1";
                errorJson.message = "访问服务器失败";
                if (mContext != null && DEBUG) {
                    UIHelper.makeToast(mContext, "访问服务器失败");
                }
                if (callback != null) {
                    callback.onError(errorJson);
                }
                return;
            }

            if (response.errorBody() != null) {
                try {
                    String errorStr = response.errorBody().string();
                    Logger.i("->Request for CustomerPolicy returned error: " + errorStr);
                    ErrorJson errorJson = new ErrorJson();
                    errorJson.code = "-1";
                    errorJson.message = errorStr;
                    if (mContext != null && DEBUG) {
                        UIHelper.makeToast(mContext, "访问服务器失败，" + errorStr);
                    }
                    if (callback != null) {
                        callback.onError(errorJson);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            String result = String.valueOf(response.body());

            Logger.i("->Request for CustomerPolicy returned: " + result);

            if (PolicyResponse.isRequestSuccessful(result)) {
                if (callback != null) {
                    PolicyAllJson data = new PolicyAllJson();
                    switch (flag) {
                        case 0:
                            // 获取用户保单列表
                            data.policyList = PolicyResponse.getResponse_PolicyList(result);
                            callback.onResponse(data);
                            break;
                        case 1:
                            // 创建保单、删除保单、更新保单
                            data.policyId = PolicyResponse.getResponse_PolicyId(result);
                            callback.onResponse(data);
                            break;
                        case 2:
                            // 创建附件、删除附件
                            data.policyAttach = PolicyResponse.getResponse_AttachList(result);
                            callback.onResponse(data);
                            break;
                        case 3:
                            // 品牌列表
                            data.companyList = PolicyResponse.getResponse_CompanyList(result);
                            callback.onResponse(data);
                            break;
                        case 4:
                            // 创建推送Token
                            data.pushTokenResult = PolicyResponse.getResponse_PushToken(result);
                            callback.onResponse(data);
                            break;
                    }
                }
            } else {
                String errorStr = String.valueOf(response.body());
                if (errorStr == null) {
                    if (callback != null) {
                        callback.onError(null);
                    }
                } else {
                    if (callback != null) {
                        callback.onError(PolicyResponse.getErrorMessage(errorStr));
                    }
                }
            }
        }

        @Override
        public void onFailure(Call<JsonObject> call, Throwable t) {
            t.printStackTrace();
            if (DEBUG && mContext != null) {
                if (t != null) {
                    UIHelper.makeToast(mContext, "访问服务器失败，" + t.getMessage());
                } else {
                    UIHelper.makeToast(mContext, "访问服务器失败");
                }
            }
            if (NetUtils.isNetworkAvailable(AppContext.getInstance())) {
                ErrorJson errorJson = new ErrorJson();
                errorJson.code = "-102";
                errorJson.message = AppContext.getInstance().getString(R.string.network_fail);
                if (mContext != null && DEBUG) {
                    UIHelper.makeToast(mContext, "访问服务器失败");
                }
                if (callback != null) {
                    callback.onError(errorJson);
                    return;
                }
            }
            if (callback != null) {
                callback.onFailure(t);
            }
        }

    }

    public interface onResponseCallback {
        /**
         * 请求成功，返回数据
         *
         * @param data
         */
        void onResponse(PolicyAllJson data);

        /**
         * 返回失败，返回｛error｝
         *
         * @param error
         */
        void onError(ErrorJson error);

        /**
         * 请求失败
         *
         * @param t
         */
        void onFailure(Throwable t);
    }

}
